<template>
  <view class="container">
    <button v-if="!gameStarted" @click="startGame" class="start-button">开始游戏</button>
    <button v-if="gameStarted && !paused" @click="pauseGame" class="pause-button">暂停游戏</button>
    <button v-if="paused" @click="resumeGame" class="resume-button">继续游戏</button>
    <view class="game-board" :style="gridStyle">
      <view v-for="(tile, index) in tiles" :key="index" class="tile" @click="handleTileClick(index)">
        <view :class="['tile-inner', { revealed: tile.isRevealed }]">
          <view class="tile-front"></view>
          <!-- <view class="tile-back">{{ tile.content }}</view> -->
		  <view class="tile-back"><image style="width:100%;height:100%" mode="aspectFill" :src="tile.content"></image></view>
		  
        </view>
      </view>
    </view>
    <button v-if="gameStarted" @click="endGame" class="end-button">结束游戏</button>
    <view v-if="gameStarted" class="score-board">分数: {{ score }}</view>
    <view v-if="gameStarted" class="level-board">关卡: {{ currentLevel }}</view>
    <view v-if="gameStarted" class="timer-board">剩余时间: {{ timeLeft }}秒</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      rows: 4, // 初始行数
      cols: 4, // 初始列数
      maxRowsCols: 15, // 最大行列数
      tiles: [],
      gameStarted: false,
      paused: false,
      matchedTiles: [],
      score: 0,
      currentLevel: 1,
      totalLevels: 10,
      timeLeft: 0,
      timer: null,
      initialTime: 90,
    };
  },
  computed: {
    gridSize() {
      return this.rows * this.cols;
    },
    gridStyle() {
      return {
        'grid-template-columns': `repeat(${this.cols}, 1fr)`,
        'grid-template-rows': `repeat(${this.rows}, 1fr)`
      };
    }
  },
  onShow() {
    this.loadGame();
  },
  methods: {
    loadGame() {
      let savedGame = uni.getStorageSync('savedGame');
      if (savedGame) {
        Object.assign(this, savedGame);
        this.paused = true;
      }
    },
    saveGame() {
      let gameData = {
        rows: this.rows,
        cols: this.cols,
        tiles: this.tiles,
        gameStarted: this.gameStarted,
        paused: this.paused,
        matchedTiles: this.matchedTiles,
        score: this.score,
        currentLevel: this.currentLevel,
        timeLeft: this.timeLeft
      };
      uni.setStorageSync('savedGame', gameData);
    },
    startGame() {
      this.gameStarted = true;
      this.paused = false;
      if (!this.loadGame()) {
        this.initBoard();
        this.startTimeLimit();
      }
    },
    pauseGame() {
      this.paused = true;
      this.saveGame();
    },
    resumeGame() {
      this.paused = false;
    },
    endGame() {
      this.gameStarted = false;
      this.paused = false;
      this.resetGame();
      uni.removeStorageSync('savedGame');
    },
    resetGame() {
      this.currentLevel = 1;
      this.rows = 4;
      this.cols = 4;
      this.matchedTiles = [];
      this.score = 0;
      this.stopTimeLimit();
      this.initBoard();
    },
    handleTileClick(index) {
      if (!this.gameStarted || this.paused) {
        return;
      }
      let tile = this.tiles[index];
      if (tile.isRevealed) {
       return 
      }
	   this.$set(this.tiles, index, { ...tile, isRevealed: true });
      let revealedTiles = this.tiles.filter(t => t.isRevealed && !this.matchedTiles.includes(t.id));
      if (revealedTiles.length === 2) {
        if (revealedTiles[0].id === revealedTiles[1].id) {
          this.matchedTiles.push(revealedTiles[0].id);
          this.score += 10;
          if (this.matchedTiles.length * 2 === this.gridSize) {
            this.score += 100;
            if (this.currentLevel < this.totalLevels) {
              this.currentLevel++;
              if (this.rows < this.maxRowsCols) {
                this.rows++;
              }
              if (this.cols < this.maxRowsCols) {
                this.cols++;
              }
              this.matchedTiles = [];
              this.initBoard();
              this.startTimeLimit();
            } else {
              wx.showToast({
                title: '完成所有关卡!',
                icon: 'success',
                duration: 2000
              });
              this.endGame();
            }
          }
        } else {
          setTimeout(() => {
            this.tiles.forEach((t, idx) => {
              if (!this.matchedTiles.includes(t.id)) {
                this.$set(this.tiles, idx, { ...t, isRevealed: false });
              }
            });
          }, 1000);
        }
      }
    },
    initBoard() {
      let tiles = [];
      for (let i = 0; i < this.gridSize; i++) {
        tiles.push({
          id: Math.floor(i / 2),
          // content: `Color ${Math.floor(i / 2)}`,
		  content: `../../static/reverseBlocks/reverseBlock (${Math.floor(i / 2)}).png`,
          isRevealed: false,
        });
      }
      this.tiles = this.shuffleArray(tiles);
    },
    shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    },
    startTimeLimit() {
      this.timeLeft = this.initialTime + this.currentLevel * 30;
      this.timer = setInterval(() => {
        this.timeLeft--;
        if (this.timeLeft <= 0) {
          this.handleTimeOut();
        }
      }, 1000);
    },
    stopTimeLimit() {
      clearInterval(this.timer);
      this.timer = null;
    },
    handleTimeOut() {
      wx.showModal({
        title: '挑战失败',
        content: '是否重试本关卡？',
        success: res => {
          if (res.confirm) {
            this.retryLevel();
          } else {
            this.endGame();
          }
        }
      });
    },
    retryLevel() {
      this.stopTimeLimit();
      this.matchedTiles = [];
      this.initBoard();
      this.startTimeLimit();
    }
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.game-board {
  display: grid;
  width: 100%; /* 确保网格宽度撑满容器 */
  max-width: 100vw; /* 最大宽度不超过视口宽度 */
  grid-template-columns: repeat(auto-fill, minmax(50px, 1fr)); /* 网格列宽自适应 */
  grid-gap: 10px;
}

.tile {
  background-color: #ddd;
  position: relative;
  cursor: pointer;
  border-radius: 10px;
  padding-top: 100%; /* 保持方块的正方形 */
}

.tile-inner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  transition: transform 0.3s;
  transform-style: preserve-3d;
  border-radius: 10px;
}

.tile-front,
.tile-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  box-shadow: 0px 5px 4px rgba(0,0,0,0.2);
  
}

.tile-front {
  background-color: #76448A;
}

.tile-back {
  background-color: #5DADE2;
  transform: rotateY(180deg);
}

.revealed {
  transform: rotateY(180deg);
}
.start-button,
.pause-button,
.resume-button,
.end-button {
  margin: 20px;
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #1aad19;
  color: white;
  font-size: 16px;
  text-align: center;
}

.score-board, .level-board, .timer-board {
  margin-top: 10px;
  font-size: 16px;
  color: #333;
}

/* ... 其他按钮和面板样式 ... */

</style>

